"""
Basic Pipeline Example

This example demonstrates the complete pipeline:
1. Load Roslyn JSON output
2. Build IR
3. Normalize IR
4. Apply transformations
5. Display results
"""

import json
from pathlib import Path

from orchestrator.ir.builder import build_ir_from_roslyn_json
from orchestrator.ir.normalizer import normalize_ir
from orchestrator.transforms.registry import get_global_registry
from orchestrator.transforms.statements import register_default_statement_transformers


def main() -> None:
    """Run the basic pipeline example"""

    # Get test data directory
    test_data = Path(__file__).parent.parent / "tests" / "test_data"

    # 1. Load Roslyn JSON output
    print("=" * 70)
    print("Step 1: Load Roslyn JSON Output")
    print("=" * 70)

    calculator_json = (test_data / "sample_roslyn_output.json").read_text()
    print(f"Loaded: sample_roslyn_output.json ({len(calculator_json)} bytes)")
    print()

    # 2. Build IR from JSON
    print("=" * 70)
    print("Step 2: Build IR from Roslyn JSON")
    print("=" * 70)

    classes = build_ir_from_roslyn_json(calculator_json)
    calc_class = classes[0]

    print(f"Built IR for class: {calc_class.name}")
    print(f"  Namespace: {calc_class.namespace}")
    print(f"  Modifiers: {', '.join(calc_class.modifiers)}")
    print(f"  Fields: {len(calc_class.fields)}")
    print(f"  Properties: {len(calc_class.properties)}")
    print(f"  Methods: {len(calc_class.methods)}")
    print(f"  Constructors: {len(calc_class.constructors)}")
    print()

    # Display members
    print("Members:")
    for field in calc_class.fields:
        print(f"  Field: {field.field_type} {field.name} ({', '.join(field.modifiers)})")

    for prop in calc_class.properties:
        print(f"  Property: {prop.property_type} {prop.name} ({', '.join(prop.modifiers)})")

    for method in calc_class.methods:
        params = ", ".join(f"{p.param_type} {p.name}" for p in method.parameters)
        print(f"  Method: {method.return_type} {method.name}({params})")

    print()

    # 3. Normalize IR
    print("=" * 70)
    print("Step 3: Normalize IR for C++ Generation")
    print("=" * 70)

    normalized = normalize_ir(calc_class)

    print(f"Normalized class: {normalized.name}")
    print(f"  Fields: {len(normalized.fields)} (was {len(calc_class.fields)})")
    print(f"  Methods: {len(normalized.methods)} (was {len(calc_class.methods)})")
    print()

    print("Transformations applied:")
    from orchestrator.ir.normalizer import IRNormalizer

    normalizer = IRNormalizer()
    normalizer.normalize(calc_class)
    for transformation in normalizer.transformations_applied:
        print(f"  - {transformation}")
    print()

    # Display normalized members
    print("Normalized Members:")
    print("\nFields:")
    for field in normalized.fields:
        metadata = field.metadata.get("generated_from", "original")
        print(f"  {field.field_type} {field.name} ({', '.join(field.modifiers)}) [{metadata}]")

    print("\nMethods:")
    for method in normalized.methods:
        params = ", ".join(f"{p.param_type} {p.name}" for p in method.parameters)
        metadata = method.metadata.get("generated_from", "original")
        modifiers = ", ".join(method.modifiers)
        print(f"  {method.return_type} {method.name}({params}) [{modifiers}] [{metadata}]")

    print()

    # 4. Apply transformations
    print("=" * 70)
    print("Step 4: Apply Statement Transformations")
    print("=" * 70)

    # Register default transformers
    register_default_statement_transformers()
    registry = get_global_registry()

    print(f"Registered transformers: {registry.get_rule_count()}")
    for rule_name in registry.list_rules():
        rule = registry.get_rule(rule_name)
        if rule:
            print(f"  - {rule.metadata.name} (priority: {rule.metadata.priority})")
    print()

    # Example: Transform a foreach statement
    from orchestrator.ir.nodes import ForeachStatement

    print("Example: Transform foreach statement")
    foreach_stmt = ForeachStatement(
        variable_type="var", variable_name="item", collection="items", body="Process(item);"
    )

    print(
        f"  Original: foreach ({foreach_stmt.variable_type} {foreach_stmt.variable_name} in {foreach_stmt.collection})"
    )

    from orchestrator.transforms.rules import TransformationPhase

    transformed = registry.apply_phase(foreach_stmt, TransformationPhase.NORMALIZATION)

    print(
        f"  Transformed: for ({transformed.variable_type} {transformed.variable_name} : {transformed.collection})"
    )
    print(f"  Metadata: {transformed.metadata}")
    print()

    # 5. Serialize IR to JSON
    print("=" * 70)
    print("Step 5: Serialize IR to JSON")
    print("=" * 70)

    json_output = normalized.model_dump_json(indent=2)
    print(f"Serialized IR ({len(json_output)} bytes):")
    print(json_output[:500] + "...")
    print()

    # Summary
    print("=" * 70)
    print("Pipeline Complete!")
    print("=" * 70)
    print("\nSummary:")
    print(f"  Input: Roslyn JSON ({len(calculator_json)} bytes)")
    print(f"  IR Classes: {len(classes)}")
    print(f"  Normalized Methods: {len(normalized.methods)}")
    print(f"  Normalized Fields: {len(normalized.fields)}")
    print(f"  Transformers Applied: {registry.get_rule_count()}")
    print(f"  Output: JSON IR ({len(json_output)} bytes)")
    print()
    print("Next step: Generate C++ code from normalized IR (Phase 2.3-2.4)")


if __name__ == "__main__":
    main()
